# run in same directory as mdf files:
#
# python mdf2reg.py
#
# needs pyfits library:
# http://www.stsci.edu/resources/software_hardware/pyfits/Download

import pyfits

def write_ds9reg(filename, xvals, yvals, colour='cyan', tag='all',
                 coord='PHYSICAL',ptype='x'):
    """Write a region file for ds9.

    colour is one of: cyan blue magenta red green yellow white black

    coord is one of:

    PHYSICAL                # pixel coords of original file using LTM/LTV 
    IMAGE                   # pixel coords of current file 
    FK4, B1950              # sky coordinate systems (degrees by default)
    FK5, J2000              # sky coordinate systems 
    GALACTIC                # sky coordinate systems 
    ECLIPTIC                # sky coordinate systems 
    ICRS                    # currently same as J2000 
    LINEAR                  # linear wcs as defined in file 
    AMPLIFIER               # mosaic coords of original file using ATM/ATV 
    DETECTOR                # mosaic coords of original file using DTM/DTV 
    """
    
    regions = ['global font="helvetica 10 normal" select=1 highlite=1 '
               'edit=0 move=1 delete=1 include=1 fixed=0 source']
    regions.append(coord)

    for i,(x,y) in enumerate(zip(xvals, yvals)):
        vals = (x, y, ptype, i+1, colour, tag)
        format = 'point(%12.8f,%12.8f) # point=%s text={%s} color=%s tag={%s}'
        regions.append(format % vals)

    open(filename,'w').write('\n'.join(regions))
    
filenames = 'm1mdf m2mdf m3mdf m4mdf m5mdf m6mdf m7mdf'.split()
colours = 'cyan blue magenta red green yellow white'.split()

for i,filename in enumerate(filenames):
    col = colours[i % len(colours)]
    f = pyfits.open(filename)
    obj = f[1].data            # OBJCAT extension data table
    ra = [float(item) for item in obj.RA_OBJ]
    dec = [float(item) for item in obj.DEC_OBJ]
    regname = 'm%d_nhmc.reg' % (i+1)
    write_ds9reg(regname, ra, dec, tag='m%d' % (i+1), colour=col,
                 coord='J2000', ptype='diamond')
    f.close()
